package org.csu.springjpetstore.controller;

import org.csu.springjpetstore.domain.Account;
import org.csu.springjpetstore.domain.Cart;
import org.csu.springjpetstore.domain.CartItem;
import org.csu.springjpetstore.persistence.ShoppingCartDAO;
import org.csu.springjpetstore.service.CartService;
import org.csu.springjpetstore.service.CatalogServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;

/**
 * @projectName: SpringJPetstore
 * @package: org.csu.springjpetstore.controller
 * @className: cartController
 * @author: suqianbei
 * @description: TODO
 * @date: 2022/3/13 14:27
 * @version: 1.0
 */
@SessionAttributes(value = {"cart", "message", "msg"})
@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    CartService cartService;
    @Autowired
    CatalogServiceImpl catalogService;
    @Autowired
    ShoppingCartDAO shoppingCartDAO;

    @GetMapping("/addItemToCart")
    public String addItemToCart(Model model, @SessionAttribute("loginUser") Account loginUser, @Autowired HttpServletRequest request) {
        String VIEW_CART = "/WEB-INF/jsp/cart/Cart.html";
        String LOGIN_HTML = "/WEB-INF/jsp/account/SignOnForm.html";
        String workingItemId;
        Cart cart;
        workingItemId = request.getParameter("workingItemId");
        boolean isInCart = false;
        if (loginUser == null) {
            return "account/SignOnForm";
        }

        //CartItem 可以实现添加n个该商品
        List<CartItem> list = cartService.getCartListByName(loginUser.getUsername());
        for (CartItem cartItem1 : list) {
            if (cartItem1.getItem().getItemId().equals(workingItemId)) {
                //购物车中有该商品
                isInCart = true;
                shoppingCartDAO.updateQuantityByUserName(loginUser.getUsername(), workingItemId, cartItem1.getQuantity() + 1);
            }
        }
        System.out.println(isInCart);
        if (!isInCart) {
            CartItem cartItem = new CartItem();
            cartItem.setItem(catalogService.getItem(workingItemId));
            cartItem.setQuantity(1);
            cartItem.setInStock(false);
            cartService.addIntoCart(loginUser.getUsername(), cartItem);
        }

        //重新获取购物车
        cart = cartService.getCartByName(loginUser.getUsername());


        model.addAttribute("cart", cart);
        return "cart/Cart";
    }

    @GetMapping("/viewCart")
    public String ViewCart(Model model, @SessionAttribute("cart") Cart cart, @SessionAttribute("loginUser") Account loginUser) {
        if (loginUser.getUsername() == null) {
            model.addAttribute("msg", "请先登录");
            return "common/Error";
        }
        if (cart.getCartItemList() == null) {
            cart = cartService.getCartByName(loginUser.getUsername());
            System.out.println(cart);
            model.addAttribute("cart", cart);
        }
        System.out.println(loginUser);
        return "cart/Cart";
    }

    @GetMapping("/removeItemFromCart")
    public String RemoveItemFromCart(Model model, @SessionAttribute("cart") Cart cart, @SessionAttribute("loginUser") Account loginUser, @Autowired HttpServletRequest request) {
        String workingItemId;
        String VIEW_CART = "/WEB-INF/jsp/cart/Cart.html";
        final String ERROE = "/WEB-INF/jsp/common/Error.html";
        workingItemId = request.getParameter("workingItemId");
        System.out.println(workingItemId);
        if (workingItemId == null || workingItemId.equals("")) {
            model.addAttribute("message", "购物车内没有该物品");
            return "common/Error";
        }
        cartService.deleteInCart(loginUser.getUsername(), workingItemId);
        //重新获取购物车。
        cart = cartService.getCartByName(loginUser.getUsername());
        model.addAttribute("cart", cart);
        return "cart/Cart";
    }

    @GetMapping("/updateCartQuantities")
    public void updateCartQuantities(Model model, @SessionAttribute("loginUser") Account loginUser, @SessionAttribute("quantity") int quantity, @Autowired HttpServletResponse response) {
        String username = (String) model.getAttribute("username");
        String itemId = (String) model.getAttribute("itemId");

        //账号匹配 地址栏用户名与session中(Account)loginUser的username是否一致
        if (username == null || loginUser == null) {
//            request.getRequestDispatcher(MAIN_FORM).forward(request, response);
//            System.out.println("run1");
            return;
        }
        if (!username.equals(loginUser.getUsername())) {
            //非法途径
            //地址栏用户名与session中用户名不一致
            //todo 可以做一个弹窗警告 https://blog.csdn.net/NewBie_xW/article/details/108598765
            System.out.println("run2");
            return;

        }

        //匹配成功
        cartService.deleteInCart(loginUser.getUsername(), itemId);
        CartItem cartItem = new CartItem();
        cartItem.setItem(catalogService.getItem(itemId));
        cartItem.setQuantity(quantity);
        cartItem.setInStock(true);
        cartService.addIntoCart(loginUser.getUsername(), cartItem);
        Cart cart = new Cart();
        cart = cartService.getCartByName(username);
        BigDecimal total = cart.getItemTotal(itemId);
        BigDecimal subTotal = cart.getSubTotal();
        response.setContentType("text/plain");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //todo data用于返回给JS代码 感觉得修改一下 不清晰 用JSON??
        String data = total + "," + subTotal;
        out.print(data);//返回给JS
        out.flush();
        out.close();

        //更新session中购物车数据
        model.addAttribute("cart", cartService.getCartByName(loginUser.getUsername()));
    }

    @GetMapping("itemQuantity")
    public void ItemQuantityChange(@Autowired HttpServletRequest req, @Autowired HttpServletResponse resp) {
        HttpSession session = req.getSession();
        String result = "Same";
        String certainItem = req.getParameter("ItemID");
        int certainItemQuantity = Integer.parseInt(req.getParameter("ItemQuantity"));
        Cart cart = (Cart) session.getAttribute("cart");
        for (CartItem cartItem : cart.getCartItemList()) {
            if (cartItem.getItem().getItemId().equals(certainItem)) {
//                    cartDAO.updateQuantityByUserName(account.getUsername(), cartItem.getItem().getItemId(), Integer.parseInt(req.getParameter(cartItem.getItem().getItemId())));
                if (cartItem.getQuantity() != certainItemQuantity)
                    result = "Different";
            }
        }
        resp.setContentType("text/plain");
        PrintWriter out = null;
        try {
            out = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print(result);
        out.flush();
        out.close();
    }

    @GetMapping("setQuantity")
    public void SetQuantityServlet(@Autowired HttpServletRequest req, @Autowired HttpServletResponse resp) {
        System.out.println(1);
        HttpSession session = req.getSession();
        String result = "0";
        Account account = (Account) session.getAttribute("loginUser");
        String certainItem = req.getParameter("ItemID");
        int certainItemQuantity = Integer.parseInt(req.getParameter("ItemQuantity"));
        Cart cart = (Cart) session.getAttribute("cart");
        for (CartItem cartItem : cart.getCartItemList()) {
            if (cartItem.getItem().getItemId().equals(certainItem)) {
                shoppingCartDAO.updateQuantityByUserName(account.getUsername(), cartItem.getItem().getItemId(), certainItemQuantity);
                cartItem.setQuantity(certainItemQuantity);
                result = String.valueOf(cartItem.getCartItemTotal());
            }
        }
        resp.setContentType("text/plain");
        PrintWriter out = null;
        try {
            out = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print(result);
        out.flush();
        out.close();
    }

    @GetMapping("resetQuantity")
    public void ResetQuantity(@Autowired HttpServletRequest req, @Autowired HttpServletResponse resp) {
        HttpSession session = req.getSession();
        String result = "0";
        String certainItem = req.getParameter("ItemID");
        Cart cart = (Cart) session.getAttribute("cart");
        for (CartItem cartItem : cart.getCartItemList()) {
            if (cartItem.getItem().getItemId().equals(certainItem)) {
                result = String.valueOf(cartItem.getQuantity());
            }
        }
        resp.setContentType("text/plain");
        PrintWriter out = null;
        try {
            out = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print(result);
        out.flush();
        out.close();
    }
}


